package com.xyz.keshe;

import android.app.AlertDialog;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.xyz.keshe.adapter.AdminManageAdapter;
import com.xyz.keshe.dao.AdminDao;
import com.xyz.keshe.db.DatabaseHelper;
import com.xyz.keshe.model.Admin;

import java.util.List;

public class AdminManageActivity extends AppCompatActivity {

    private ListView listViewAdmins;
    private Button btnAddAdmin;
    private AdminManageAdapter adapter;
    private AdminDao adminDao;
    private List<Admin> adminList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_admin_manage);

        // 初始化数据库
        adminDao = new AdminDao(this);

        // 只在首次启动时清理数据库
        cleanupDatabaseOnce();

        // 初始化视图
        listViewAdmins = findViewById(R.id.listview_admins);
        btnAddAdmin = findViewById(R.id.btn_add_admin);

        // 加载管理员列表
        loadAdmins();

        // 添加管理员按钮点击事件
        btnAddAdmin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showAddAdminDialog();
            }
        });
    }

    private void loadAdmins() {
        adminList = adminDao.getAllAdmins();
        adapter = new AdminManageAdapter(this, adminList, new AdminManageAdapter.OnAdminActionListener() {
            @Override
            public void onEdit(Admin admin) {
                showEditAdminDialog(admin);
            }

            @Override
            public void onDelete(Admin admin) {
                showDeleteConfirmDialog(admin);
            }
        });
        listViewAdmins.setAdapter(adapter);
    }

    private void showAddAdminDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("添加管理员");

        View dialogView = getLayoutInflater().inflate(R.layout.dialog_add_admin, null);
        EditText etUsername = dialogView.findViewById(R.id.et_admin_username);
        EditText etPassword = dialogView.findViewById(R.id.et_admin_password);
        CheckBox cbIsSuper = dialogView.findViewById(R.id.cb_is_super);

        // 禁用超级管理员选项 - 只有admin用户可以是超级管理员
        cbIsSuper.setEnabled(false);
        cbIsSuper.setChecked(false);

        builder.setView(dialogView);
        builder.setPositiveButton("添加", (dialog, which) -> {
            String username = etUsername.getText().toString().trim();
            String password = etPassword.getText().toString().trim();
            boolean isSuper = cbIsSuper.isChecked();

            if (TextUtils.isEmpty(username)) {
                Toast.makeText(this, "用户名不能为空", Toast.LENGTH_SHORT).show();
                return;
            }

            if (TextUtils.isEmpty(password)) {
                Toast.makeText(this, "密码不能为空", Toast.LENGTH_SHORT).show();
                return;
            }

            if (password.length() < 6) {
                Toast.makeText(this, "密码长度不能少于6位", Toast.LENGTH_SHORT).show();
                return;
            }

            // 检查用户名是否已存在
            if (adminDao.getAdminByUsername(username) != null) {
                Toast.makeText(this, "用户名已存在", Toast.LENGTH_SHORT).show();
                return;
            }

            Admin admin = new Admin();
            admin.setUsername(username);
            admin.setPassword(password);
            // 强制设置为普通管理员
            admin.setIsSuper(false);

            long result = adminDao.insertAdmin(admin);
            if (result > 0) {
                Toast.makeText(this, "添加成功", Toast.LENGTH_SHORT).show();
                loadAdmins();
            } else {
                Toast.makeText(this, "添加失败", Toast.LENGTH_SHORT).show();
            }
        });
        builder.setNegativeButton("取消", null);
        builder.show();
    }

    private void showEditAdminDialog(Admin admin) {
        // admin用户不能被编辑
        if ("admin".equals(admin.getUsername())) {
            Toast.makeText(this, "默认管理员账号不能被编辑", Toast.LENGTH_SHORT).show();
            return;
        }

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("编辑管理员");

        View dialogView = getLayoutInflater().inflate(R.layout.dialog_add_admin, null);
        EditText etUsername = dialogView.findViewById(R.id.et_admin_username);
        EditText etPassword = dialogView.findViewById(R.id.et_admin_password);
        CheckBox cbIsSuper = dialogView.findViewById(R.id.cb_is_super);

        // 填充现有数据
        etUsername.setText(admin.getUsername());
        etPassword.setText(admin.getPassword());
        cbIsSuper.setChecked(admin.getIsSuper());

        // 禁用超级管理员选项 - 只有admin用户可以是超级管理员
        cbIsSuper.setEnabled(false);
        cbIsSuper.setChecked(false);

        builder.setView(dialogView);
        builder.setPositiveButton("保存", (dialog, which) -> {
            String username = etUsername.getText().toString().trim();
            String password = etPassword.getText().toString().trim();
            boolean isSuper = cbIsSuper.isChecked();

            if (TextUtils.isEmpty(username)) {
                Toast.makeText(this, "用户名不能为空", Toast.LENGTH_SHORT).show();
                return;
            }

            if (TextUtils.isEmpty(password)) {
                Toast.makeText(this, "密码不能为空", Toast.LENGTH_SHORT).show();
                return;
            }

            if (password.length() < 6) {
                Toast.makeText(this, "密码长度不能少于6位", Toast.LENGTH_SHORT).show();
                return;
            }

            // 如果用户名改变了，检查新用户名是否已存在
            if (!username.equals(admin.getUsername())) {
                if (adminDao.getAdminByUsername(username) != null) {
                    Toast.makeText(this, "用户名已存在", Toast.LENGTH_SHORT).show();
                    return;
                }
            }

            admin.setUsername(username);
            admin.setPassword(password);
            // 强制设置为普通管理员
            admin.setIsSuper(false);

            int result = adminDao.updateAdmin(admin);
            if (result > 0) {
                Toast.makeText(this, "更新成功", Toast.LENGTH_SHORT).show();
                loadAdmins();
            } else {
                Toast.makeText(this, "更新失败", Toast.LENGTH_SHORT).show();
            }
        });
        builder.setNegativeButton("取消", null);
        builder.show();
    }

    private void showDeleteConfirmDialog(Admin admin) {
        // admin用户不能被删除
        if ("admin".equals(admin.getUsername())) {
            Toast.makeText(this, "默认管理员账号不能被删除", Toast.LENGTH_SHORT).show();
            return;
        }

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("确认删除");
        builder.setMessage("确定要删除管理员 \"" + admin.getUsername() + "\" 吗？");
        builder.setPositiveButton("删除", (dialog, which) -> {
            int result = adminDao.deleteAdmin(admin.getId());
            if (result > 0) {
                Toast.makeText(this, "删除成功", Toast.LENGTH_SHORT).show();
                loadAdmins();
            } else {
                Toast.makeText(this, "删除失败", Toast.LENGTH_SHORT).show();
            }
        });
        builder.setNegativeButton("取消", null);
        builder.show();
    }

    private void cleanupDatabaseOnce() {
        // 使用SharedPreferences记录是否已经清理过
        String prefName = "admin_cleanup";
        String keyName = "cleaned";
        
        if (getSharedPreferences(prefName, MODE_PRIVATE).getBoolean(keyName, false)) {
            return; // 已经清理过了，不再执行
        }
        
        try {
            boolean hasChanges = false;
            
            // 删除admin3用户（如果存在）
            int deleted = adminDao.deleteAdminByUsername("admin3");
            if (deleted > 0) {
                hasChanges = true;
            }

            // 移除所有非admin用户的超级管理员权限
            int updated = adminDao.removeAllSuperAdminExceptDefault();
            if (updated > 0) {
                hasChanges = true;
            }
            
            // 标记为已清理
            getSharedPreferences(prefName, MODE_PRIVATE)
                .edit()
                .putBoolean(keyName, true)
                .apply();
                
            // 只有在有实际变更时才显示提示
            if (hasChanges) {
                Toast.makeText(this, "数据库权限已优化", Toast.LENGTH_SHORT).show();
            }
        } catch (Exception e) {
            // 静默处理错误，不影响正常使用
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        loadAdmins();
    }
} 